<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class LoginForm extends CFormModel
{
	public $zm_name;
	public $zm_psword;
	public $rememberMe;
	//定义变量。存放验证码
	public $verifyCode;
	private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('verifyCode,zm_name, zm_psword', 'required'),
			// rememberMe needs to be a boolean
			array('rememberMe', 'boolean'),
			// password needs to be authenticated
			array('zm_psword', 'authenticate'),
				
			array('verifyCode','captcha'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'rememberMe'=>'记住密码',
			'zm_name'=>'用户名',
			'zm_psword'=>'密码',
			'verifyCode'=>'验证码',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->zm_name,$this->zm_psword);
			if(!$this->_identity->authenticate())
				$this->addError('zm_psword','用户名或者密码错误，请重新输入！');
		}
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->zm_name,$this->zm_psword);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			$this->_identity->setState('expire', $duration+time());
			if($this->rememberMe){
				$loginInfo = Yii::app()->securityManager->encrypt(serialize(array('zm_name'=>$this->zm_name,'zm_psword'=>$this->zm_psword)));
				$loginInfo = Yii::app()->securityManager->hashData($loginInfo);
				$cookie = new CHttpCookie('loginInfo',$loginInfo);
				$cookie->expire = $duration+time();
				Yii::app()->request->cookies['loginInfo'] = $cookie;
			}elseif(isset(Yii::app()->request->cookies['loginInfo'])){
				unset(Yii::app()->request->cookies['loginInfo']);
			}
			
			Yii::app()->user->login($this->_identity);
			return true;
		}
		else
			return false;
	}
	

}
